/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hyce;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import javax.swing.JOptionPane;
import pl.edu.zut.wi.vsl.commons.Message;
import pl.edu.zut.wi.vsl.commons.StegoImage;
import pl.edu.zut.wi.vsl.commons.StegoPackage;
import pl.edu.zut.wi.vsl.commons.steganography.DecodingException;
import pl.edu.zut.wi.vsl.commons.steganography.EncodingException;
import pl.edu.zut.wi.vsl.modules.steganography.lsb.LsbImpl;

/**
 *
 * @author Hiding Team
 */
public class HidingTool {
    private File f;
    /**
     *
     */
    public HidingTool(){
    }

    /**
     * @param String msg is the message to hide.
     * @param filepath is the filepath of a png image
     *
     * @return String is the file path to the file that was created. null if an error occurred.
     */
    public String hide(String msg, String filepath){

        try {
            f = new File(filepath);
            byte[] bytes = msg.getBytes(Charset.forName("ISO-8859-1"));
            Message m = new Message(bytes);

            try {
                StegoImage si = new StegoImage(f);
                StegoPackage sp = new StegoPackage(si, m);
                si.flush();

                LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
                map.put("startbits", "0");
                map.put("endbits", "1");

                LsbImpl lsb = new LsbImpl();

                try {
                    //Create filepath to save to.
                    int cutIndex = filepath.lastIndexOf("\\");
                    String hyFilePath = filepath.substring(0, cutIndex+1) +
                                             f.getName().substring(0, f.getName().length()-4)
                                             + "HY.png";

                    StegoImage sf = lsb.encode(sp, map);
                    sf.write(hyFilePath);

                    return hyFilePath;

//                    try {
//                        Message mb = lsb.decode(sf, map);
//
//                    } catch (DecodingException ex) {
//                        System.out.println("Error decoding Message: " + ex.getMessage());
//                    }

                } catch (EncodingException ex) {
                    System.out.println("Error encoding: " + ex.getMessage());
                }

            } catch (IOException ex) {
                System.out.println("Error creating StegoImage and Package: " + ex.getMessage());
            }
        }
        catch(Exception e){
            System.out.println("Error: " + e. getMessage());
            return null;
        }
        return null;
    }
}
